package com.bondex.charter.service;

import com.alibaba.fastjson.JSON;
import com.bondex.charter.commons.BookingProcessTypeEnum;
import com.bondex.charter.commons.BusinessTypeEnum;
import com.bondex.charter.commons.CharterStatusEnum;
import com.bondex.charter.commons.CutoffProcessTypeEnum;
import com.bondex.charter.commons.*;
import com.bondex.charter.dao.CharterBookingMapper;
import com.bondex.charter.dao.CharterSiMapper;
import com.bondex.charter.dao.CharterSiUnconfirmedMapper;
import com.bondex.charter.dao.CharterUserOperateLogMapper;
import com.bondex.charter.po.*;
import com.bondex.charter.pojo.DetailPageOutT;
import com.bondex.charter.utils.Base64Util;
import com.bondex.global.commons.GlobalConst;
import com.bondex.global.pojo.ResultT;
import com.bondex.global.utils.DateUtil;
import com.bondex.viresult.dto.BondexMailDTO;
import com.bondex.viresult.dto.MailMsgResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 截单后台服务
 * Created by JD on 2021/9/16.
 */
@Service
public class SIService {
    private Logger logger = LoggerFactory.getLogger(SIService.class);
    @Resource
    private CharterBookingMapper charterBookingMapper;
    @Resource
    private CharterSiMapper charterSiMapper;
    @Resource
    private CharterSiUnconfirmedMapper charterSiUnconfirmedMapper;
    @Resource
    private CharterUserOperateLogMapper charterUserOperateLogMapper;
    @Resource
    private BaseService baseService;
    @Autowired
    private TdJsonService tdJsonService;
    @Autowired
    private MailUtil mailUtil;

    /**
     * 截单页面保存操作
     * @param charterSiSaveVO
     * @return
     */
    @Transactional
    public ResultT saveBIInfo(CharterSiSaveVO charterSiSaveVO) {
        ResultT resultT = new ResultT();
        try {
            if (null != charterSiSaveVO) {
                if(Integer.parseInt(charterSiSaveVO.getSiStatus())>=CharterStatusEnum.SI_NEW.getValueDB()){
                    logger.error("截单委托号["+charterSiSaveVO.getOrderNo()+"]明细页面保存操作失败：单据状态未达已截单，请刷新后重试");
                    resultT.setSuccess(false);
                    resultT.setMessage("保存失败：单据状态未达已截单，请刷新页面后重试");
                    return resultT;
                }
                //更新前台传参
                int i = charterSiMapper.updateBIInfoByOrderNo(charterSiSaveVO);
                if(i == 0){
                    logger.error("截单委托号["+charterSiSaveVO.getOrderNo()+"]明细页面保存操作失败：单据状态已变动，请刷新页面后重试");
                    resultT.setSuccess(false);
                    resultT.setMessage("保存失败：单据状态已变动，请刷新页面后重试");
                    return resultT;
                }
                resultT.setSuccess(true);
                resultT.setMessage("保存成功！！！");
                //保存用户操作日志
                charterUserOperateLogMapper.insertCharterUserOperateLog(new CharterUserOperateLogVO(
                        BusinessTypeEnum.CUTOFF.getName(),
                        CutoffProcessTypeEnum.CUTOFF_SAVE.getName(),
                        charterSiSaveVO.getOrderNo(),
                        null,
                        charterSiSaveVO.getBlNo(),
                        charterSiSaveVO.getCustomerNo(),
                        charterSiSaveVO.getOperatorId(),
                        JSON.toJSONString(charterSiSaveVO),
                        JSON.toJSONString(resultT),
                        charterSiSaveVO.getUserName()
                ));
                baseService.refreshBulkyHeavyFlagOfSi(charterSiSaveVO.getOrderNo());
            } else {
                resultT.setSuccess(false);
                resultT.setMessage("保存入参不可为空！！！");
            }
        } catch (Exception e) {
            logger.error("截单委托号["+charterSiSaveVO.getOrderNo()+"]明细页面保存操作失败：" + e.getMessage());
            resultT.setSuccess(false);
            resultT.setMessage("操作失败，请联系管理员。");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }
    /**
     * 格式单生成
     * @param charterReqSiForBusinessReq 格式单生成参数VO
     * @return Result
     */
    @Transactional
    public ResultT<Object> updateAndBillCreate(CharterReqSiForBusinessReq charterReqSiForBusinessReq) {
        ResultT<Object> resultT = new ResultT<>();
        if (null == charterReqSiForBusinessReq || null == charterReqSiForBusinessReq.getCharterSiSaveVO()) {
            resultT.setMessage("入参为空，格式单生成失败！");
            resultT.setSuccess(false);
            return resultT;
        }
        CharterSiSaveVO charterSiSaveVO = charterReqSiForBusinessReq.getCharterSiSaveVO();
        try {
            if (!GlobalConst.ZERO.equals(charterSiSaveVO.getSiStatus())) {
                resultT.setMessage("截单状态不为\"截单待确认\",格式单生成失败");
                logger.info("委托单号 " + charterSiSaveVO.getOrderNo() + " 截单状态不为\"截单待确认\",格式单生成失败！！");
            }else {
                //设置发送邮件参数并发送邮件
                BondexMailDTO bondexMailDTO = new BondexMailDTO();
                bondexMailDTO.setId(Const.SI_DRAFT_TEMPLETE_ID);
                bondexMailDTO.setReceiveTo(charterReqSiForBusinessReq.getTo());
                bondexMailDTO.setCc(charterReqSiForBusinessReq.getCc());
                bondexMailDTO.setSubject(Const.SI_DRAFT + charterSiSaveVO.getBlNo() + charterSiSaveVO.getOrderNo());
                //生成格式单并转换为base64流
                File file = tdJsonService.buildCutOff(charterSiSaveVO.getOrderNo());
                List<String> files = new ArrayList<>();
                files.add(Base64Util.pdfToBase64(file));
                bondexMailDTO.setBase64AttachmentsFiles(files);
                //使用base64需要传入文件名，顺序一一对应
                List<String> filesName = new ArrayList<>();
                filesName.add("DRAFT"+ charterSiSaveVO.getBlNo() + DateUtil.convertDateToString(new Date()) +".pdf");
                bondexMailDTO.setFileNames(filesName);
                MailMsgResponse mailMsgResponse = mailUtil.pushMail(bondexMailDTO);
                if (mailMsgResponse.getSuccess()) {
                    resultT.setMessage("格式单发送邮件成功");
                    logger.info("委托单号 " + charterSiSaveVO.getOrderNo() + " 格式单发送邮件成功！！");
                }else {
                    resultT.setMessage("格式单发送邮件失败");
                    logger.info("委托单号 " + charterSiSaveVO.getOrderNo() + " 格式单发送邮件失败！！");
                }
                //保存数据
                ResultT resultSave = saveBIInfo(charterSiSaveVO);
                //更新状态为已截单
                CharterSi charterSi = new CharterSi();
                charterSi.setOrderNo(charterSiSaveVO.getOrderNo());
                charterSi.setModifyBy(charterReqSiForBusinessReq.getUserName());
                charterSi.setVersion(charterSiSaveVO.getVersion() + 1);
                charterSi.setSiStatus(CharterStatusEnum.SI_CONFIRMED.getValueDBString());
                charterSiMapper.updateBIInfoForStatus(charterSi);
                if (resultSave.isSuccess()) {
                    resultT.setMessage(resultT.getMessage() + "、更新数据成功");
                    logger.info("委托单号 " + charterSiSaveVO.getOrderNo() + " 更新数据成功！！");
                }else {
                    resultT.setMessage(resultT.getMessage() + "、更新数据失败");
                    logger.info("委托单号 " + charterSiSaveVO.getOrderNo() + " 更新数据失败！！");
                }
                resultT.setSuccess(true);
            }
        }catch (Exception e) {
            logger.info("委托单号 " + charterSiSaveVO.getOrderNo() + " 格式单生成失败！！");
            resultT.setMessage("格式单生成失败,请联系管理员");
            //异常被捕获会令@Transactional事务失效，使用该方法可让spring触发事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }

    /**
     * 格式单批量生成
     * @param cutOffBillCreatesVO 1
     * @return 1
     */
    @Transactional
    public ResultT<Object> updateAndBillCreates(CutOffBillCreatesVO cutOffBillCreatesVO) {
        ResultT<Object> resultT = new ResultT<>();
        if (null == cutOffBillCreatesVO || null == cutOffBillCreatesVO.getOrderNo()) {
            resultT.setMessage("入参为空，格式单生成失败！");
            resultT.setSuccess(false);
            return resultT;
        }
        Integer successCount = 0;
        List<String> orderNos = cutOffBillCreatesVO.getOrderNo();
        for (String orderNo : orderNos) {
            CharterSi charterSi = charterSiMapper.selectByOrderNo(orderNo);
            //判断状态是都为截单待确认
            if (CharterStatusEnum.SI_NEW.getValueDBString().equals(charterSi.getSiStatus())) {
                //设置发送邮件参数并发送邮件
                BondexMailDTO bondexMailDTO = new BondexMailDTO();
                bondexMailDTO.setId(Const.SI_DRAFT_TEMPLETE_ID);
                bondexMailDTO.setReceiveTo(cutOffBillCreatesVO.getTo());
                bondexMailDTO.setCc(cutOffBillCreatesVO.getCc());
                bondexMailDTO.setSubject(Const.SI_DRAFT + charterSi.getBlNo() + charterSi.getOrderNo());
                //生成格式单并转换为base64流
                File file = tdJsonService.buildCutOff(charterSi.getOrderNo());
                List<String> files = new ArrayList<>();
                files.add(Base64Util.pdfToBase64(file));
                bondexMailDTO.setBase64AttachmentsFiles(files);
                //使用base64需要传入文件名，顺序一一对应
                List<String> filesName = new ArrayList<>();
                filesName.add("DRAFT"+ charterSi.getBlNo() + DateUtil.convertDateToString(new Date()) +".pdf");
                bondexMailDTO.setFileNames(filesName);
                MailMsgResponse mailMsgResponse = mailUtil.pushMail(bondexMailDTO);
                if (mailMsgResponse.getSuccess()) {
                    logger.info("委托单号 " + charterSi.getOrderNo() + " 格式单发送邮件成功！！");
                    successCount++;
                }else {
                    logger.info("委托单号 " + charterSi.getOrderNo() + " 格式单发送邮件失败！！");
                }
                charterSiMapper.updateBIInfoForStatus(charterSi);
            }
        }
        resultT.setMessage("已选委托单" + orderNos.size() +"条，格式单邮件发送成功" + successCount + "条，失败" + (orderNos.size() - successCount) + "条");
        resultT.setSuccess(true);
        return resultT;
    }

    /**
     * 列表处理收费改单
     * @param charterSiForAmendmentReq
     * @return
     */
    public ResultT handleBIInfoForAmendmentList(CharterReqSiForBusinessListReq charterSiForAmendmentReq) {
        ResultT resultT = new ResultT();
        int success = 0;
        int fail = 0;
        if (null != charterSiForAmendmentReq) {
            for(CharterReqSiForBusinessVO vo:charterSiForAmendmentReq.getCharterSiForAmendmentVoList()){
                try{
                    charterSiForAmendmentReq.setOrderNo(vo.getOrderNo());
                    charterSiForAmendmentReq.setVersion(vo.getVersion());
                    if(this.updateBIInfoForAmendment(charterSiForAmendmentReq).isSuccess())
                        success++;
                    else
                        fail++;
                }catch(Exception e){
                    //冗余配置,仅仅做捕获异常处理，保证遍历正常执行
                    fail++;
                }
            }
            resultT.setSuccess(true);
            resultT.setMessage("操作结束，成功："+String.valueOf(success)+"条,失败："+String.valueOf(fail)+"条");
        } else {
            resultT.setSuccess(false);
            resultT.setMessage("改单操作入参不可为空！！！");
        }
        return resultT;
    }

    /**
     * 单个处理流程 收费改单
     * @param req
     * @return
     */
    @Transactional
    public ResultT updateBIInfoForAmendment(CharterReqBaseVO req) {
        ResultT resultT = new ResultT();
        try {
            //查询表最新数据，闸口状态之后单据才能走以下流程
            CharterSi charterSi = charterSiMapper.selectByOrderNo(req.getOrderNo());
            if(null!=charterSi&&Integer.parseInt(charterSi.getSiStatus())==CharterStatusEnum.SI_NEW.getValueDB()){
                logger.error("截单委托号["+ req.getOrderNo()+"]收费改单操作失败：单据状态未达已截单，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("改单失败：单据状态未达已截单，请刷新后重试");
                return resultT;
            }
            //根据前端传入版本号进行调用
            charterSi.setVersion(req.getVersion());
            charterSi.setModifyBy(req.getUserName());
            //更新数据库
            int i = charterSiMapper.updateBIInfoForAmendment(charterSi);
            if(i == 0){
                logger.error("截单委托号["+ req.getOrderNo()+"]收费改单操作失败：单据状态已变动，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("改单失败：单据状态已变动，请刷新后重试");
                return resultT;
            }
            //保存用户操作日志
            charterUserOperateLogMapper.insertCharterUserOperateLog(new CharterUserOperateLogVO(
                    BusinessTypeEnum.CUTOFF.getName(),
                    CutoffProcessTypeEnum.CUTOFF_MODIFY_REMARK.getName(),
                    charterSi.getOrderNo(),
                    null,
                    charterSi.getBlNo(),
                    charterSi.getCustomerNo(),
                    req.getOperatorId(),
                    JSON.toJSONString(req),
                    JSON.toJSONString("收费改单成功！"),
                    req.getUserName()
            ));
            resultT.setSuccess(true);
        } catch (Exception e) {
            logger.error("截单委托号["+ req.getOrderNo()+"]收费改单操作失败：" + e.getMessage());
            resultT.setSuccess(false);
            resultT.setMessage("改单失败：请联系系统管理员！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }

    /**
     * 台账标记AMS申报操作-列表
     * @param req
     * @return
     */
    public ResultT handleBIInfoForAmsFilingList(CharterReqSiForBusinessListReq req) {
        ResultT resultT = new ResultT();
        int success = 0;
        int fail = 0;
        if (null != req) {
            for(CharterReqSiForBusinessVO vo:req.getCharterSiForAmendmentVoList()){
                try{
                    req.setOrderNo(vo.getOrderNo());
                    req.setVersion(vo.getVersion());
                    if(this.updateBIInfoForAmsFiling(req).isSuccess())
                        success++;
                    else
                        fail++;
                }catch(Exception e){
                    //冗余配置,仅仅做捕获异常处理，保证遍历正常执行
                    fail++;
                }
            }
            resultT.setSuccess(true);
            resultT.setMessage("操作结束，成功："+String.valueOf(success)+"条,失败："+String.valueOf(fail)+"条");
        } else {
            resultT.setSuccess(false);
            resultT.setMessage("AMS申报入参不可为空！！！");
        }
        return resultT;
    }

    /**
     * 截单标记AMS申报操作-明细
     * @param req
     * @return
     */
    @Transactional
    public ResultT updateBIInfoForAmsFiling(CharterReqBaseVO req) {
        ResultT resultT = new ResultT();
        try {
            //查询表最新数据，闸口状态之后单据才能走以下流程
            CharterSi charterSi = charterSiMapper.selectByOrderNo(req.getOrderNo());
            if(null!=charterSi&&Integer.parseInt(charterSi.getSiStatus())!=CharterStatusEnum.SI_CONFIRMED.getValueDB()){
                logger.error("截单委托号["+ req.getOrderNo()+"]AMS申报操作失败：单据状态未达已截单，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("申报失败：单据状态未达已截单，请刷新后重试");
                return resultT;
            }
            //根据前端传入版本号进行调用
            charterSi.setVersion(req.getVersion());
            charterSi.setModifyBy(req.getUserName());
            charterSi.setSiStatus(String.valueOf(CharterStatusEnum.SI_AMS_FILING.getValueDB()));
            //更新数据库
            int i = charterSiMapper.updateBIInfoForStatus(charterSi);
            if(i == 0){
                logger.error("截单委托号["+ req.getOrderNo()+"]AMS申报操作失败：单据状态已变动，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("申报失败：单据状态已变动，请刷新后重试");
                return resultT;
            }
            //保存用户操作日志
            charterUserOperateLogMapper.insertCharterUserOperateLog(new CharterUserOperateLogVO(
                    BusinessTypeEnum.CUTOFF.getName(),
                    CutoffProcessTypeEnum.CUTOFF_AMS_REPORT.getName(),
                    charterSi.getOrderNo(),
                    null,
                    charterSi.getBlNo(),
                    charterSi.getCustomerNo(),
                    req.getOperatorId(),
                    JSON.toJSONString(req),
                    JSON.toJSONString("AMS申报成功！"),
                    req.getUserName()
            ));
            resultT.setSuccess(true);
        } catch (Exception e) {
            logger.error("截单委托号["+ req.getOrderNo()+"]AMS申报操作失败：" + e.getMessage());
            resultT.setSuccess(false);
            resultT.setMessage("申报失败：请联系系统管理员！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }

    /**
     * 根据截单号查询截单数据
     * @param orderNo 截单号
     * @return 1
     */
    public ResultT<DetailPageOutT<CharterSi,CharterSiUnconfirmed>> getSiByOrderId(String orderNo){
        ResultT<DetailPageOutT<CharterSi,CharterSiUnconfirmed>> resultT = new ResultT<DetailPageOutT<CharterSi,CharterSiUnconfirmed>>();
        if (StringUtils.isBlank(orderNo)) {
            resultT.setMessage("未设置订单号!");
            return resultT;
        }
        CharterSi charterSi = charterSiMapper.selectByOrderNo(orderNo);
        if (null != charterSi) {
            resultT.setSuccess(true);
            resultT.getData().setData(charterSi);
            if (CharterStatusEnum.SI_BL_AMENDMENT.getValueDBString().equals(charterSi.getSiStatus())) {
                CharterSiUnconfirmed charterSiUnconfirmed = charterSiUnconfirmedMapper.selectByOrderNo(orderNo);
                List<CharterSiUnconfirmed> charterSiUnconfirmedList = new ArrayList<>();
                charterSiUnconfirmedList.add(charterSiUnconfirmed);
                resultT.getData().setListOfUnconfirmed(charterSiUnconfirmedList);
            }
        }
        return resultT;
    }

    /**
     * 列表处理标记SOC
     * @param charterSiForAmendmentReq
     * @return
     */
    public ResultT handleSocMarking(CharterReqSiForBusinessListReq charterSiForAmendmentReq) {
        ResultT resultT = new ResultT();
        int success = 0;
        int fail = 0;
        if (null != charterSiForAmendmentReq) {
            for(CharterReqSiForBusinessVO vo:charterSiForAmendmentReq.getCharterSiForAmendmentVoList()){
                try{
                    charterSiForAmendmentReq.setOrderNo(vo.getOrderNo());
                    charterSiForAmendmentReq.setVersion(vo.getVersion());
                    if(this.updateSocMarking(charterSiForAmendmentReq).isSuccess())
                        success++;
                    else
                        fail++;
                }catch(Exception e){
                    //冗余配置,仅仅做捕获异常处理，保证遍历正常执行
                    fail++;
                }
            }
            resultT.setSuccess(true);
            resultT.setMessage("SOC打标结束，成功："+String.valueOf(success)+"条,失败："+String.valueOf(fail)+"条");
        } else {
            resultT.setSuccess(false);
            resultT.setMessage("打标操作入参不可为空！！！");
        }
        return resultT;
    }

    /**
     * 单个处理流程 可直接处理明细按钮
     * @param req
     * @return
     */
    @Transactional
    public ResultT updateSocMarking(CharterReqBaseVO req) {
        ResultT resultT = new ResultT();
        try {
            //查询表最新数据，闸口状态之后单据才能走以下流程
            CharterSi charterSi = charterSiMapper.selectByOrderNo(req.getOrderNo());
            if(null!=charterSi&&Integer.parseInt(charterSi.getSiStatus())==CharterStatusEnum.SI_NEW.getValueDB()){
                logger.error("截单委托号["+ req.getOrderNo()+"]打标操作失败：单据状态未达已截单，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("打标失败：单据状态未达已截单，请刷新后重试");
                return resultT;
            }
            //根据前端传入版本号进行调用
            charterSi.setVersion(req.getVersion());
            charterSi.setModifyBy(req.getUserName());
            //更新数据库
            int i = charterSiMapper.updateMarkSoc(charterSi);
            if(i == 0){
                logger.error("截单委托号["+ req.getOrderNo()+"]打标操作失败：单据状态已变动，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("打标失败：单据状态已变动，请刷新后重试");
                return resultT;
            }
            //保存用户操作日志
            charterUserOperateLogMapper.insertCharterUserOperateLog(new CharterUserOperateLogVO(
                    BusinessTypeEnum.CUTOFF.getName(),
                    CutoffProcessTypeEnum.SOC.getName(),
                    charterSi.getOrderNo(),
                    null,
                    charterSi.getBlNo(),
                    charterSi.getCustomerNo(),
                    req.getOperatorId(),
                    JSON.toJSONString(req),
                    JSON.toJSONString("SOC打标成功！"),
                    req.getUserName()
            ));
            resultT.setSuccess(true);
        } catch (Exception e) {
            logger.error("截单委托号["+ req.getOrderNo()+"]打标操作失败：" + e.getMessage());
            resultT.setSuccess(false);
            resultT.setMessage("打标失败：单据状态已变动，请刷新后重试");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }

    /**
     * 列表处理甩货
     * @param charterSiForAmendmentReq
     * @return
     */
    public ResultT handleDumpGoods(CharterReqSiForBusinessListReq charterSiForAmendmentReq) {
        ResultT resultT = new ResultT();
        int success = 0;
        int fail = 0;
        if (null != charterSiForAmendmentReq) {
            for(CharterReqSiForBusinessVO vo:charterSiForAmendmentReq.getCharterSiForAmendmentVoList()){
                try{
                    charterSiForAmendmentReq.setOrderNo(vo.getOrderNo());
                    charterSiForAmendmentReq.setVersion(vo.getVersion());
                    if(this.updateDumpGoods(charterSiForAmendmentReq).isSuccess())
                        success++;
                    else
                        fail++;
                }catch(Exception e){
                    //冗余配置,仅仅做捕获异常处理，保证遍历正常执行
                    fail++;
                }
            }
            resultT.setSuccess(true);
            resultT.setMessage("甩货结束，成功："+String.valueOf(success)+"条,失败："+String.valueOf(fail)+"条");
        } else {
            resultT.setSuccess(false);
            resultT.setMessage("甩货操作入参不可为空！！！");
        }
        return resultT;
    }

    /**
     * 单个处理流程 可直接处理明细按钮
     * @param req
     * @return
     */
    @Transactional
    public ResultT updateDumpGoods(CharterReqBaseVO req) {
        ResultT resultT = new ResultT();
        try {
            //查询表最新数据，闸口状态之后单据才能走以下流程
            CharterBooking charterBooking = charterBookingMapper.selectByOrderNo(req.getOrderNo());
            CharterSi charterSi = charterSiMapper.selectByOrderNo(req.getOrderNo());
            if(null!=charterSi&&Integer.parseInt(charterSi.getSiStatus())==CharterStatusEnum.SI_NEW.getValueDB()){
                logger.error("截单委托号["+ req.getOrderNo()+"]甩货操作失败：单据状态未达已截单，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("甩货失败：单据状态未达已截单，请刷新后重试");
                return resultT;
            }
            //根据前端传入版本号进行调用
            charterBooking.setVersion(req.getVersion());
            charterBooking.setModifyBy(req.getUserName());
            //更新数据库
            int i = charterBookingMapper.updateDumpGoods(charterBooking);
            if(i == 0){
                logger.error("截单委托号["+ req.getOrderNo()+"]甩货操作失败：单据状态已变动，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("甩货失败：单据状态已变动，请刷新后重试");
                return resultT;
            }
            //保存用户操作日志
            charterUserOperateLogMapper.insertCharterUserOperateLog(new CharterUserOperateLogVO(
                    BusinessTypeEnum.BOOKING.getName(),
                    BookingProcessTypeEnum.BOOKING_ROLL_OVER.getName(),
                    charterSi.getOrderNo(),
                    null,
                    charterSi.getBlNo(),
                    charterSi.getCustomerNo(),
                    req.getOperatorId(),
                    JSON.toJSONString(req),
                    JSON.toJSONString("甩货成功！"),
                    req.getUserName()
            ));
            resultT.setSuccess(true);
        } catch (Exception e) {
            logger.error("截单委托号["+ req.getOrderNo()+"]甩货操作失败：" + e.getMessage());
            resultT.setSuccess(false);
            resultT.setMessage("甩货失败：单据状态已变动，请刷新后重试");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }

    /**
     * 截单提单签发操作-明细
     * @param req
     * @return
     */
    @Transactional
    public ResultT updateBIInfoForConfirm(CharterReqBaseVO req) {
        ResultT resultT = new ResultT();
        try {
            //查询表最新数据，闸口状态之后单据才能走以下流程
            CharterSi charterSi = charterSiMapper.selectByOrderNo(req.getOrderNo());
            if(null!=charterSi&&Integer.parseInt(req.getVersion())!=CharterStatusEnum.SI_BL_AMENDMENT.getValueDB()){
                logger.error("截单委托号["+ req.getOrderNo()+"]截单更改操作失败：单据状态未达截单更改，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("截单更改失败：单据状态已变化，请刷新后重试");
                return resultT;
            }
            //根据前端传入版本号进行调用
            charterSi.setVersion(req.getVersion());
            charterSi.setModifyBy(req.getUserName());
            charterSi.setSiStatus(String.valueOf(CharterStatusEnum.SI_CONFIRMED.getValueDB()));
            //更新数据库
            int i = charterSiMapper.updateBIInfoForStatus(charterSi);
            if(i == 0){
                logger.error("截单委托号["+ req.getOrderNo()+"]AMS操作失败：单据状态已变动，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("申报失败：单据状态已变动，请刷新后重试");
                return resultT;
            }
            //更新数据库 根据前端进参进行判断是通过还是驳回 CUTOFF_MODIFY_PASS  CUTOFF_MODIFY_NOT_PASS





            //保存用户操作日志
            charterUserOperateLogMapper.insertCharterUserOperateLog(new CharterUserOperateLogVO(
                    BusinessTypeEnum.CUTOFF.getName(),
                    CutoffProcessTypeEnum.CUTOFF_AMS_REPORT.getName(),
                    charterSi.getOrderNo(),
                    null,
                    charterSi.getBlNo(),
                    charterSi.getCustomerNo(),
                    req.getOperatorId(),
                    JSON.toJSONString(req),
                    JSON.toJSONString("AMS申报成功！"),
                    req.getUserName()
            ));
        } catch (Exception e) {
            logger.error("截单委托号["+ req.getOrderNo()+"]AMS申报操作失败：" + e.getMessage());
            resultT.setSuccess(false);
            resultT.setMessage("申报失败：请联系系统管理员！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }

    /**
     * 台账提单签发操作-列表
     * @param req
     * @return
     */
    public ResultT handleBIInfoForReleaseList(CharterReqSiForBusinessListReq req) {
        ResultT resultT = new ResultT();
        int success = 0;
        int fail = 0;
        if (null != req) {
            for(CharterReqSiForBusinessVO vo:req.getCharterSiForAmendmentVoList()){
                try{
                    req.setOrderNo(vo.getOrderNo());
                    req.setVersion(vo.getVersion());
                    if(this.updateBIInfoForRelease(req).isSuccess())
                        success++;
                    else
                        fail++;
                }catch(Exception e){
                    //冗余配置,仅仅做捕获异常处理，保证遍历正常执行
                    fail++;
                }
            }
            resultT.setSuccess(true);
            resultT.setMessage("操作结束，成功："+String.valueOf(success)+"条,失败："+String.valueOf(fail)+"条");
        } else {
            resultT.setSuccess(false);
            resultT.setMessage("AMS申报入参不可为空！！！");
        }
        return resultT;
    }

    /**
     * 截单提单签发操作-明细
     * @param req
     * @return
     */
    @Transactional
    public ResultT updateBIInfoForRelease(CharterReqBaseVO req) {
        ResultT resultT = new ResultT();
        try {
            //订舱甩货不能签发

            //查询表最新数据，闸口状态之后单据才能走以下流程
            CharterSi charterSi = charterSiMapper.selectByOrderNo(req.getOrderNo());
            if(null!=charterSi&&Integer.parseInt(charterSi.getSiStatus())!=CharterStatusEnum.SI_AMS_FILING.getValueDB()){
                logger.error("截单委托号["+ req.getOrderNo()+"]提单签发操作失败：单据状态未达AMS已申报，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("提单签发：请选择AMS已申报单据");
                return resultT;
            }
            //根据前端传入版本号进行调用
            charterSi.setVersion(req.getVersion());
            charterSi.setModifyBy(req.getUserName());
            charterSi.setSiStatus(String.valueOf(CharterStatusEnum.SI_BL_RELEASE.getValueDB()));
            //更新数据库
            int i = charterSiMapper.updateBIInfoForStatus(charterSi);
            if(i == 0){
                logger.error("截单委托号["+ req.getOrderNo()+"]提单签发操作失败：单据状态已变动，请刷新后重试");
                resultT.setSuccess(false);
                resultT.setMessage("提单签发失败：单据状态已变动，请刷新后重试");
                return resultT;
            }
            //保存用户操作日志
            charterUserOperateLogMapper.insertCharterUserOperateLog(new CharterUserOperateLogVO(
                    BusinessTypeEnum.CUTOFF.getName(),
                    CutoffProcessTypeEnum.CUTOFF_BL.getName(),
                    charterSi.getOrderNo(),
                    null,
                    charterSi.getBlNo(),
                    charterSi.getCustomerNo(),
                    req.getOperatorId(),
                    JSON.toJSONString(req),
                    JSON.toJSONString("提单签发成功！"),
                    req.getUserName()
            ));
        } catch (Exception e) {
            logger.error("截单委托号["+ req.getOrderNo()+"]提单签发操作失败：" + e.getMessage());
            resultT.setSuccess(false);
            resultT.setMessage("申报失败：请联系系统管理员！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultT;
    }
}
